define(['jquery', 'select2', 'datetimepicker', 'mapController', "controller","rights","coordtransform","moment","validate","mapview"], function ($) {
    // 方法重定向
    var c = require("controller");
    var rights = require("rights");
    var mapController = require("mapController");
    var moment = require("moment");
    var coordtransform = require("coordtransform");
    var mapview = require("mapview");

    var tHeight = $(window).height() - 50 - 35;
    $(".content").height(tHeight);

    return {
        init: function () {
            // test set token
            // localStorage.setItem('token', 'MiMxNDcyNjk0Mjk4QGcuZmx5LWNsb3VkLmNuI1pjZDYzQ2tqeXg1MzdHSkRQWU43SEkxUS9Ecz0=');
            this.searchData={};
            this.initDataTable();
            this.bindEvent();
        },
        dataTable: null,
        delRow: null,
        searchData: {},
        initDataTable: function () {
            var self = this;
            this.dataTable = c.myDataTable($("#mmg"), {
                ajax: function (data, callback, settings) {
                    //封装请求参数
                    var param = {
                        page_no: (data.start / data.length),
                        page_size: data.length
                    };
                    $.extend(true, param, self.searchData);
                    //ajax请求数据
                    c.ajax({
                        url: "element/search",
                        cache: false, //禁用缓存
                        data: param, //传入组装的参数
                        dataType: "json",
                        success: function (result) {
                            //封装返回数据
                            var returnData = {};
                            returnData.draw = data.draw;//这里直接自行返回了draw计数器,应该由后台返回
                            returnData.recordsTotal = result.count;//返回数据全部记录
                            returnData.recordsFiltered = result.count;//后台不实现过滤功能，每次查询均视作全部结果
                            returnData.data = result.elements;//返回的数据列表
                            //console.log(returnData);
                            //调用DataTables提供的callback方法，代表数据已封装完成并传回DataTables进行渲染
                            //此时的数据需确保正确无误，异常判断应在执行此回调前自行处理完毕
                            callback(returnData);
                        }
                    });
                },
                scrollY: (tHeight - 210) + "px",
                scrollCollapse: true,
                columns: [
                    {"data": "id"},
                    {"data": "cid"},
                    {"data": "name"},
                    {"data": "type"},
                    {"data": "expire"},
                    {"data": "property"}
                ],
                columnDefs: [
                    {
                        "targets": 1,//所在公司列
                        "data": "cid",
                        "render": function (data, type, row) {
                            return data==0?'所有公司':c.getCompanys(row.cid);
                        }
                    },
                    {
                        "targets": 3,//类型
                        "data": "type",
                        "render": function (data, type, row) {
                            switch (row.type) {
                                case 0:
                                    return '起降点';
                                case 1:
                                    return '途经点';
                                case 2:
                                    return '加油点';
                                case 3:
                                    return '机场';
                                case 252:
                                    return '往返';
                                case 253:
                                    return '圆形空域';
                                case 254:
                                    return '航线';
                                case 255:
                                    return '多边形空域';
                            }
                        }
                    },
                    {
                        "targets": 4,//有效日期
                        "data": "expire",
                        "render": function (data, type, row) {
                            return data==0?'永久':c.formatYMDFromInt(row.expire);
                        }
                    },
                    /*{
                        "targets": 5,//详情信息
                        "data": "property",
                        "render": function (data, type, row) {
                            var result = '';
                            var tempParam = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
                            var property = row.property;
                            property = JSON.parse(property);
                            if (row.type == 0) {
                                result = row.name + ' ( ' + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )';
                            } else if (row.type == 253) {
                                result = row.name + ' ( '
                                    + property.path[0].name + ': ' + property.path[0].lng + ' , ' + property.path[0].lat + ' )'
                                    + ' )<br>(半径:' + property.radius + '米)';
                            } else {
                                $.each(property.path, function (i) {
                                    result += tempParam.substring(i, i + 1)
                                        + ' ( ' + property.path[i].name + ': ' + property.path[i].lng + ' , ' + property.path[i].lat + ' )<br>';
                                });
                            }
                            return result;

                        }
                    },*/
                    {
                        // 定义操作列,######以下是重点########
                        "targets": 5,//操作按钮目标列
                        "data": null,
                        "render": function (data, type, row) {
                            var html = "<div class='btn-group'>" +
                                "<a href='#' class='btn btn-sm btn-info edit' data-toggle='modal' data-target='#myModal' data-rights='5004'><i class='fa fa-edit'></i>编辑</a>" +
                                "<a href='#' class='btn btn-sm btn-danger' data-rights='5005'><i class='fa fa-remove'></i>删除</a>" +
                                "<a href='#' class='btn btn-sm btn-vk see' data-toggle='modal' data-target='#myModal' data-rights='5002'><i class='fa fa-eye'></i>查看</a>" +
                                "</div>";
                            return html;
                        }
                    }],
                drawCallback: function(settings, json) {
                    rights.isShowFn($('.content'));
                }
            });
        },
        bindEvent: function () {
            var self = this;
            var dataSee = '';
            //添加
            $('#add').on('click', function () {
                $("#myModal>.modal-dialog").load("element/form.html", function () {
                    self.formInit()

                });
            });
            $('#mmg').on('click', '.edit', function () {
                //编辑
                dataSee = 0;
                var dataRow = self.dataTable.row($(this).parents('tr')).data();
                $("#myModal>.modal-dialog").load("element/form.html", function () {
                    self.formInit(dataRow,dataSee)
                });
            }).on('click', '.see', function () {
                //查看
                dataSee = 1;
                var dataRow = self.dataTable.row($(this).parents('tr')).data();
                $("#myModal>.modal-dialog").load("element/view.html", function () {
                    self.viewInit(dataRow)
                });
            }).on('click', '.btn-danger', function () {
                //删除
                self.delRow = $(this).parents('tr')
                var dataRow = self.dataTable.row(self.delRow).data();
                c.confirm({
                    content: "是否删除",
                    confirm: function () {
                        c.ajax({
                                url: "element/delete",
                                data: {
                                    cid: dataRow.cid,
                                    id: dataRow.id
                                },
                                success: function (res) {
                                    if (res.err < 0) {
                                        alert(res.msg);
                                        return
                                    }
                                    self.dataTable.ajax.reload();
                                    /*self.dataTable.row($('.J_remove'))
                                     .remove().draw();*/
                                }
                            }
                        )
                    }
                })
                })
                .on('click', 'tr', function () {
                    $(this).siblings().removeClass("select");
                    $(this).toggleClass("select");
                });
            $('#search').on('click', function () {
                self.searchData = {

                };
                var name = $('#searchName').val();
                var etype = $('#searchEtype').val();
                // var property = $('#searchProperty').val();

                if(name!=''){
                    self.searchData.name = name
                }
                if(etype!=''){
                    self.searchData.etype = etype
                }
                // if(property!=''){
                //     self.searchData.property = property
                // }
                self.dataTable.draw();
            });


            $('[name="role"]').on('change', function () {
                if ($('[name="role"]').val() === "CORP") {
                    $(".company").removeClass('hide');
                } else {
                    $(".company").addClass('hide');
                }
            });

            $('.search-input').on('keyup', function () {
                console.log(this.value);
                // self.dataTable.search(this.value, false, false).draw();
            })

        },
        formInit: function (dataRow,dataSee) {
            var self = this;
            var $form = $('.edit-form');
            //获取公司
            var Companys=c.getAllCompanys();
            var nn=[];//公司临时数组
            $.each(Companys,function (i,v) {
                nn.push({id:v.cid,text:v.name})
            });
            $("#companys").select2({
                data:nn
            });
            //本地时间
            $("#expire").datetimepicker({
                locale: 'zh-CN',
                format: 'YYYY-MM-DD',
                minDate:moment().add(0, 'days').format('YYYY-MM-DD')
            });
            // 显示地图前判断
            $('#placeChoice').on('click', function () {
                var nType = $('input:radio[name="type"]:checked').val();
                $("#mapModal>.modal-dialog").load("element/mapform.html", function () {
                    $('#mapModal').modal('show');
                    self.mapForm(nType)
                });
            });

            $('input:radio[name="type"]').on('change', function() {
                $('.coData').removeData('property').empty();
            });

            $('#expireCK').on('click', function() {
                if($(this).is(':checked')){
                    $('#expire').val('').prop('readonly',true);
                }else{
                    $('#expire').removeAttr('readonly')
                }
            });


            if (dataRow) {//判断是否编辑
                var fTime = c.formatYMDFromInt(dataRow.expire);
                if(dataRow.expire==0){
                    $('#expireCK').trigger("click")
                }
                var type = dataRow.type;
                $form.children("#did").hide();
                $form.find('[name="expire"]').val(fTime);
                $form.find('[name="name"]').val(dataRow.name);
                $form.find('[name="cid"]').val(dataRow.cid).trigger("change");
                $form.find('[name="id"]').val(dataRow.id);

                $('input[id="'+type+'"]').attr("checked",'true');
                var property=JSON.parse(dataRow.property);

                $('.coData').data('property',property);
                $.each(property.path,function (i,piont) {
                    var title=piont.name;
                    if(property['radius']){
                        title+='(半径'+property['radius']+'米)';
                    }
                    $('.coData').append('<span class="label label-success">'+title+'</span>');
                });

                $('#myModal').find('.modal-title').text('编辑飞行要素');

            }

            $('.edit-form').validate({
                submitHandler: function (form) {
                    var mode = $('#myModal').find('.modal-title').text();
                    var formData = new FormData($('.edit-form').get(0));
                    // var fdata =  Date.parse(formData.get('expire')) / 1000;
                    var type = $(':radio[name="type"]:checked').val();

                    var params = {
                        cid: formData.get('cid'),
                        name: formData.get('name'),
                        etype: type,
                        expire: formData.get('expire'),
                        property: property
                    };

                    if($(this).is(':checked')||params.expire==""){
                        params.expire=0
                    }else{
                        params.expire=Date.parse(formData.get('expire')) / 1000;
                    }

                    if(!$('.coData').data('property')){
                        c.alert({
                            content:'请选取坐标'
                        });
                        return false;

                    }else{
                        var property=JSON.stringify($('.coData').data('property'));
                        params.property=property;
                    }

                    if (params.role === 'CORP') {
                        params['cid'] = formData.get('cid')
                    }
                    var url='element/';
                    if (mode === "添加飞行要素") {
                        url+= 'create';
                    } else if(mode === "编辑飞行要素"){
                        url+= 'update';
                        params.id = formData.get('id')
                    }
                    c.ajax({
                        url: url,
                        dataType: "json",
                        cache: false,
                        data: params,
                        success: function (res) {

                            if (res.err == 0) {
                                $('#myModal').modal('hide');
                                self.dataTable.ajax.reload();
                            }

                        }
                    });
                }
            })
        },
        viewInit: function (dataRow) {
            var self = this;
            var $form = $('.edit-form');






            if (dataRow) {//
                var fTime =dataRow.expire==0?'永久有效': c.formatYMDFromInt(dataRow.expire);
                $form.children("#did").hide();
                $form.find('[name="expire"]').val(fTime);
                $form.find('[name="name"]').val(dataRow.name);
                $form.find('[name="companys"]').val(c.getCompanys(dataRow.cid));
                $form.find('[name="id"]').val(dataRow.id);

                $form.find('[name="type"]').val(c.getElementType(dataRow.type));
                var property=JSON.parse(dataRow.property);
                $('.coData').data('property',property);
                $.each(property.path,function (i,piont) {
                    var title=piont.name;
                    if(property['radius']){
                        title+='(半径'+property['radius']+'米)';
                    }
                    $('.coData').append('<span class="label label-success">'+title+'</span>');
                });

                // 显示地图前判断
                $('#placeChoice').on('click', function () {
                    $("#mapModal>.modal-dialog").load("element/mapview.html", function () {
                        $('#mapModal').modal('show');
                        mapview.init([dataRow])
                    });
                });

            }

        },
        mapForm:function (type) {
            $('#container').height($('#mapModal .modal-dialog').height()-$('#mapModal .modal-header').height()-$('#mapModal .modal-footer').height()-50);
            var property=$('.coData').data('property');
            c.conLog(property);
            var map = mapController.initMap();
            map.init('container');
            var Satellite=map.setMapType();
            map.setMapControl();
            $(".maptype>div:eq(0)").on('click',function () {
                Satellite.hide();
            });
            $(".maptype>div:eq(1)").on('click',function () {
                Satellite.show();
            });
            var points=[];
            var marks=[];
            var space=null;
            switch(type) {
                case "254": //画航线
                    space=map.createPolyline([{lng:0,lat:0}],{
                        strokeColor: '#e63f00',
                        strokeOpacity: 1,
                        strokeWeight: 3,
                        zIndex:10,
                        strokeStyle: "solid"
                    });

                    break;
                case "255": // 多边形空域
                    space=map.createPolygon([{lng:0,lat:0}],{
                        fillColor:'#289BEC',
                        fillOpacity:0.4,
                        strokeColor:'#40A4FB',
                        zIndex:10,
                        strokeWeight:2
                    });
                    break;
                case "253":// 圆形空域
                    space=map.createCircle([{lng:0,lat:0}],{
                        fillColor:'#289BEC',
                        fillOpacity:0.4,
                        strokeColor:'#40A4FB',
                        zIndex:10,
                        radius:0,
                        strokeWeight:2
                    });
                    break;
            }
            if (space){
                map.addOverlay(space);
            }

            if(property){
                $.each(property.path,function (i,point) {
                    var lng=point.lng;
                    var lat=point.lat;
                    var wgs= coordtransform.wgs84togcj02(mapController.changeDMSToLng(lng),mapController.changeDMSToLat(lat));
                    points.push({lng:wgs[0],lat:wgs[1]});
                    var mk=map.createMark({
                        lnglat: points[i],
                        label:{content:'<div class="my-makrlabel">'+(i+1)+'</div>',offset:[0,0]}
                    });

                    marks.push(mk);
                    map.addOverlay(mk);
                    var radius=0;
                    if(type=="254"||type=="255"){
                        setSpace(points)
                    }else if(type=="253"){
                        setCenter(points);
                        setRadius(parseFloat(property.radius));
                        radius=property.radius;
                    }
                    addHtml((i+1),point,radius)
                });

                map.setFitView()
            }

            function addHtml(i,point,radius) {
                var html='<input type="text" data-id="place" value="'+point.name+'"/>';//'<span>'+(i+1)+'</span><input type="text" data-id="place" value="'+point.name+'"/>';
                html+='<input type="text" data-id="lngX" value="'+point.lng+'"/>';
                html+='<input type="text" data-id="latY" value="'+point.lat+'"/>';
                if(type=="253"){
                    html+='<input type="text" data-id="radius" value="'+radius+'"/>';
                }
                // html+='<a href="#" class="fa fa-fw fa-remove"></a> </li>';
                var clone=$('.cloneDIV>div').clone();
                clone.find('.box-body').append(html);
                clone.find('.box-title').append('<span>点位：'+i+'</span>');
                $('.ele-location').append(clone);
            }
            map.addEventListener('click',function (e) {
                var i=marks.length+1;
                if(type=="254"||type=="255"){
                    createmarker(e,i);
                    setSpace(points);
                }else{
                    if(i==1){
                        createmarker(e,i);
                    }else{
                        updateMarker(e,0);
                    }
                    if(type=="253"){
                        setCenter(points);
                        setRadius(2000);
                    }

                }
            });
            $('.ele-location').on('click','.mapremove',function () {//删除点事件
                var div= $(this).parents('.box-primary');
                var i= div.index();
                map.remove([marks[i]]);
                points.splice(i,1);
                marks.splice(i,1);
                div.remove();
                if(type=="254"||type=="255"){
                    setSpace(points)
                }else if(type=="253"){
                    setCenter(points);
                }
                resetMarker(i);
                //splice
            }).on('input','input[data-id="lngX"],input[data-id="latY"]',function () {//改变坐标时
                var div= $(this).parents('.box-primary');
                var i= div.index();
                var lng=div.find('input[data-id="lngX"]').val();
                var lat=div.find('input[data-id="latY"]').val();
                var wgs= coordtransform.wgs84togcj02(mapController.changeDMSToLng(lng),mapController.changeDMSToLat(lat));
                points[i]={lng:wgs[0],lat:wgs[1]};
                marks[i].setPosition(points[i]);
                if(type=="254"||type=="255"){
                    setSpace(points)
                }else if(type=="253"){
                    setCenter(points);
                }
            }).on('input','input[data-id="radius"]',function () {//改变半径时
                setRadius(parseFloat($(this).val()));
            });


            function setSpace(points) {
                if(space){
                    space.setPath(points);
                }

            }//设置空域
            function setCenter(points) {//设置圆形空域中心点
                if(space){
                    if(points.length==0){
                        space.setCenter([{lng:0,lat:0}]);
                    }else{
                        space.setCenter(points);
                    }

                }
            }
            function setRadius(radius) {//设置圆形空域半径
                if(space){
                    space.setRadius(radius);
                }
            }
            //刷新点信息
            function resetMarker(count) {
                for(var i=count;i<marks.length;i++){
                    marks[i].setLabel({content:'<div class="my-makrlabel">'+(i+1)+'</div>',offset:[0,0]});
                    $('.ele-location>div').eq(i).find('.box-title span').text((i+1));
                }
            }
            //创建 点
            function createmarker(e,i){
                var mk=map.createMark({
                    lnglat:e,
                    label:{content:'<div class="my-makrlabel">'+i+'</div>',offset:[0,0]}
                });
                marks.push(mk);
                map.addOverlay(mk);
                points.push(e);
                map.getAddress(e,function (addressComponent) {
                    var wgs= coordtransform.gcj02towgs84(e.lng,e.lat);
                    /*var html='<li><span>'+i+'</span><input type="text" data-id="place" value="'+addressComponent.city+addressComponent.district+addressComponent.street+'"/>';
                    html+='<input type="text" data-id="lngX" value="'+mapController.changeLngToDMS(wgs[0])+'"/>';
                    html+='<input type="text" data-id="latY" value="'+mapController.changeLatToDMS(wgs[1])+'"/>';
                    if(type=="253"){
                        html+='<input type="text" data-id="radius" value="2000"/>';
                    }
                    html+='<a href="#" class="fa fa-fw fa-remove"></a> </li>';
                    $('.ele-location').append(html);*/
                    addHtml(i,{
                        name:addressComponent.city+addressComponent.district+addressComponent.street,
                        lng:mapController.changeLngToDMS(wgs[0]),
                        lat:mapController.changeLatToDMS(wgs[1])
                    },2000)
                });
            }
            //更新点
            function updateMarker(e,i){
                marks[i].setPosition(e);
                points[i]=e;
                map.getAddress(e,function (addressComponent) {
                    var wgs= coordtransform.gcj02towgs84(e.lng,e.lat);
                    /*var html='<li><span>'+(i+1)+'</span><input type="text" data-id="place" value="'+addressComponent.city+addressComponent.district+addressComponent.street+'"/>';
                    html+='<input type="text" data-id="lngX" value="'+mapController.changeLngToDMS(wgs[0])+'"/>';
                    html+='<input type="text" data-id="latY" value="'+mapController.changeLatToDMS(wgs[1])+'"/>';
                    if(type=="253"){
                        html+='<input type="text" data-id="radius" value="'+space.getRadius()+'"/>';
                    }
                    html+='<a href="#" class="fa fa-fw fa-remove"></a> </li>';
                    $('.ele-location').html(html);*/
                    $('.ele-location').empty();
                    addHtml((i+1),{
                        name:addressComponent.city+addressComponent.district+addressComponent.street,
                        lng:mapController.changeLngToDMS(wgs[0]),
                        lat:mapController.changeLatToDMS(wgs[1])
                    },2000)
                });
            }

            $('#map_submit').on('click',function (e) {
                var returnData={
                    path:[]
                };
                $('.coData').empty();
                $('.ele-location>div').each(function (e) {
                    var div=$(this);
                    var title="";
                    var liData={
                        lng:div.find('input[data-id="lngX"]').val(),
                        lat:div.find('input[data-id="latY"]').val(),
                        name:div.find('input[data-id="place"]').val()
                    };
                    returnData.path.push(liData);
                    title=liData.name;
                    if(type=="253"){
                        returnData['radius']=div.find('input[data-id="radius"]').val();
                        title+='(半径'+returnData['radius']+'米)';
                    }
                    $('.coData').append('<span class="label label-success">'+title+'</span>');
                });
                $('.coData').data('property',returnData);
                $('#mapModal').modal('hide');
            })

        }
    }
});



